package com.ruoyi.common.baidu;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import org.codehaus.jettison.json.JSONObject;
import com.alibaba.fastjson.JSONArray;
import com.ruoyi.common.utils.CommonUtil;
import com.ruoyi.common.utils.http.HttpClientUtil;

/**
 * 	百度实名认证
 * @author DEREK
 *
 */
public class AuthService {

	public static String APPID = "47130983";

	public static String AK = "Y0lRl968PyCaYcmGKq8rHA3e";

	public static String SK = "g7DsNYfouB2rIuCUO9jIlwV0yZM8S39C";


	/**
	 * 获取权限token
	 * @return 返回示例：
	 * {
	 * "access_token": "24.460da4889caad24cccdb1fea17221975.2592000.1491995545.282335-1234567",
	 * "expires_in": 2592000
	 * }
	 */
	public static String getAuth() {
		// 官网获取的 API Key 更新为你注册的
		String clientId = AK;
		// 官网获取的 Secret Key 更新为你注册的
		String clientSecret = SK;
		return getAuth(clientId, clientSecret);
	}
	/**
	 * 获取API访问token 和 verifyToken
	 * 该token有一定的有效期，需要自行管理，当失效时需重新获取.
	 * @param ak - 百度云官网获取的 API Key
	 * @param sk - 百度云官网获取的 Securet Key
	 */
	public static String getAuth(String ak, String sk) {
		// 获取token地址
		String authHost = "https://aip.baidubce.com/oauth/2.0/token?";
		String getAccessTokenUrl = authHost
				// 1. grant_type为固定参数
				+ "grant_type=client_credentials"
				// 2. 官网获取的 API Key
				+ "&client_id=" + ak
				// 3. 官网获取的 Secret Key
				+ "&client_secret=" + sk;
		try {
			URL realUrl = new URL(getAccessTokenUrl);
			// 打开和URL之间的连接
			HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
			connection.setRequestMethod("GET");
			connection.connect();
			// 获取所有响应头字段
			// 定义 BufferedReader输入流来读取URL的响应
			BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			String result = "";
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
			JSONObject jsonObject = new JSONObject(result);
			String access_token = jsonObject.getString("access_token");
			return access_token;
		} catch (Exception e) {
			return "";
		}
	}

	/**
	 * 	获取 VerifyToken 
	 * @return
	 */
	public static Map<String,Object> getVerifyToken(){
		Map<String,Object> retMap = new HashMap<String, Object>();
		retMap.put("code",500);
		try {
			String accessToken = getAuth();
			String url = "https://aip.baidubce.com/rpc/2.0/brain/solution/faceprint/verifyToken/generate?access_token="+accessToken;
			Map<String, String> param = new HashMap<String, String>();
			param.put("plan_id", "18916");
			net.sf.json.JSONObject fromObject = net.sf.json.JSONObject.fromObject(param);
			String doPostJson = HttpClientUtil.doPostJson(url, fromObject.toString());
			JSONObject verify = new JSONObject(doPostJson);
			System.out.println("获取 VerifyToken :"+verify);
			if(null != verify) {
				if(verify.getBoolean("success")) {
					retMap.put("code", 200);
					retMap.put("accessToken",accessToken);
					retMap.put("verifyToken", verify.getJSONObject("result").getString("verify_token"));
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			retMap.put("code", 500);
		}
		return retMap;
		
	}
	
	/**
	 * 	获取活体检测结果
	 * @param accessToken
	 * @param verifyToken
	 */
	//https://ai.baidu.com/ai-doc/FACE/aknovy94h#1%E8%8E%B7%E5%8F%96%E8%AE%A4%E8%AF%81%E4%BA%BA%E8%84%B8%E6%8E%A5%E5%8F%A3
	public static AppUserAuth resultDetail(String accessToken,String verifyToken) {
		AppUserAuth userAuth = null;
		try {
			// 获取实名认证查询结果
			String url = "https://aip.baidubce.com/rpc/2.0/brain/solution/faceprint/result/detail?access_token="+accessToken;
			Map<String, String> param = new HashMap<String, String>();
			param.put("verify_token", verifyToken);
			net.sf.json.JSONObject fromObject = net.sf.json.JSONObject.fromObject(param);
			String doPostJson = HttpClientUtil.doPostJson(url, fromObject.toString());
			System.out.println("认证结果返回："+doPostJson);
			JSONObject resultObject = new JSONObject(doPostJson);
			if(null != resultObject && resultObject.getBoolean("success")) {
				// 获取用户图片信息
				String imgUrl = "https://aip.baidubce.com/rpc/2.0/brain/solution/faceprint/result/simple?access_token="+accessToken;
				String imgJson = HttpClientUtil.doPostJson(imgUrl, fromObject.toString());
				System.out.println("图片返回结果:"+imgJson);
				JSONObject imgResultObject = new JSONObject(imgJson);
				if(null != imgResultObject && resultObject.getBoolean("success")) {
					userAuth = new AppUserAuth();
					// 解析用户数据
					JSONObject result = resultObject.getJSONObject("result").getJSONObject("idcard_confirm");
					userAuth.setIdCard(result.getString("idcard_number"));
					userAuth.setName(result.getString("name"));
					userAuth.setImage(imgResultObject.getJSONObject("result").getString("image"));
				}
			}
			return userAuth;
		} catch (Exception e) {
			e.printStackTrace();
			return userAuth;
		}
	}
	
	/**
	 * 	百度 图片比对
	 * @param accessToken		百度token
	 * @param sourceImg			图片1
	 * @param targetImg			图片2
	 * @return
	 */
	public static double compareFaces(String accessToken,String sourceImg,String targetImg) {
		String url = "https://aip.baidubce.com/rest/2.0/face/v3/match?access_token="+accessToken;
		sourceImg = CommonUtil.getScanImg(sourceImg);
		targetImg = CommonUtil.getScanImg(targetImg);
		double compareFaces = 0;
		try {
			com.alibaba.fastjson.JSONObject img1 = new com.alibaba.fastjson.JSONObject();
			img1.put("image", sourceImg);
			img1.put("image_type", "URL");
			com.alibaba.fastjson.JSONObject img2 = new com.alibaba.fastjson.JSONObject();
			img2.put("image", targetImg);
			img2.put("image_type", "URL");
			JSONArray jsonArr = new JSONArray();
			jsonArr.add(img1);
			jsonArr.add(img2);
			String doPostJson = HttpClientUtil.doPostJson(url, jsonArr.toString());
			JSONObject result = new JSONObject(doPostJson);
			if(result.getString("error_msg").equals("SUCCESS")) {
				compareFaces = result.getJSONObject("result").getDouble("score"); 
			}
			return compareFaces;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return compareFaces;
	}
	
	public static void main(String[] args) throws Exception {
//		String auth = getAuth();
//		System.out.println(auth);
//		String token = "24.3794c6d59f40a298d45b2796330be5d6.2592000.1688350740.282335-34334461";
//		double compareFaces = compareFaces(token, "https://oss.kouyouapp.com/auth/20220711151054132023.png", "https://oss.kouyouapp.com/pic/16784296063436.jpg");
//		System.out.println(compareFaces);
		Map<String, Object> verifyToken = getVerifyToken();
		System.out.println(verifyToken.toString());
		
	}
}
